﻿/**
 * 
 */
package com.sshc625.io {
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	
	/**
	 * 
	 * @author sshc625
	 */
	public class FileDownloader extends EventDispatcher {
		
		public static var PROGRESS:String 	= "LoadProgress";
		public static var COMPLETE:String 	= "LoadComplete";
		public static var OPEN:String 		= "LoadOpen";
		public static var ERROR:String 		= "LoadError";
		
		// file reference
		protected var fRef:FileReference;
		// file download url
		protected var fileUrl:String;
		// file name to save
		protected var fileName:String;
		
		// error string
		private var _error:String;
		// progress
		private var _progress:Number;
		// total bytes
		private var _total:Number;
		// loaded bytes
		private var _loaded:Number;
		
		public function FileDownloader(file:String, name:String) {
			// download file ref
			fRef = new FileReference();
			fRef.addEventListener(ProgressEvent.PROGRESS, reportProgress);
			fRef.addEventListener(IOErrorEvent.IO_ERROR, errorReport);
			fRef.addEventListener(Event.OPEN, startLoad);
			fRef.addEventListener(Event.COMPLETE, endLoad);
			
			fileUrl = file;
			//name = name.replace(/[^\w\s-_.,+=()~!?]/g,'');
			//name = name.replace('.mp3', '');
			//fileName = name+".mp3";
			fileName = name;
		}
		
		public function get progress():Number{
			return this._progress;
		}
		
		public function get bytesTotal():Number{
			return this._total;
		}
		public function get bytesLoaded():Number{
			return this._loaded;
		}
		
		public function get error():String{
			return this._error;
		}
		
		public function doDownload():void{
			var req:URLRequest = new URLRequest(fileUrl);
			fRef.download(req, fileName);
		}
		
		protected function errorReport (e:IOErrorEvent):void{
			this._error = e.text;
			dispatchEvent(new Event(FileDownloader.ERROR));
		}
		
		protected function reportProgress(evt:ProgressEvent):void{
			this._loaded = new Number(evt.bytesLoaded/(1024*1024));
			this._total = new Number(evt.bytesTotal/(1024*1024));
			if (this._total > 100){
				this._total = -1;
				this._progress = new Number( -1 );
			}else{
				this._progress = new Number( this._loaded/this._total*100 );
			}
			dispatchEvent(new Event(FileDownloader.PROGRESS));
		}
		
		protected function startLoad(evt:Event):void{
			dispatchEvent(new Event(FileDownloader.OPEN));
		}
		
		protected function endLoad(evt:Event):void{
			dispatchEvent(new Event(FileDownloader.COMPLETE));
		}
	}
}